<?php
/**
 * MyBB 1.6
 * Copyright 2010 MyBB Group, All Rights Reserved
 *
 * Website: http://mybb.com
 * License: http://mybb.com/about/license
 *
 * $Id: mod.php 5380 2011-02-21 12:04:43Z Otse $
 */
 
// Disallow direct access to this file for security reasons
if(!defined("IN_MYBB"))
{
	die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.");
}


$plugins->add_hook("index_start", "mod_index_start");
$plugins->add_hook("newthread_end", "mod_newthread_end");
$plugins->add_hook("editpost_end", "mod_editpost_end");
$plugins->add_hook("datahandler_post_validate_thread", "mod_datahandler_post_validate_thread");
$plugins->add_hook("datahandler_post_insert_thread_post", "mod_datahandler_post_insert_thread_post");
//$plugins->add_hook("datahandler_post_update_thread", "mod_datahandler_post_update_thread");
$plugins->add_hook("datahandler_post_validate_post", "mod_datahandler_post_validate_post");


function mod_info()
{
    return array(
	"name"			=> "Mod",
	"description"	=> "Pours a mod file managing system into the MyBB funnel.",
	"website"		=> "http://ak.fm",
	"author"		=> "Steelrat",
	"authorsite"	=> "http://ak.fm",
	"version"		=> "0.7",
	"guid" 			=> "",
	"compatibility" => "*"
    );

}

function mod_install()
{
    global $db, $lang;


    $collation = $db->build_create_table_collation();
    
    /*$sql = '
    CREATE TABLE IF NOT EXISTS `'.TABLE_PREFIX.'mod` (
    `mid` int(11) NOT NULL AUTO_INCREMENT,
    `tid` int(11) DEFAULT NULL,
    `version` varchar(5) DEFAULT NULL,
    `date` int(11) NOT NULL,
    `valid` varchar(1) DEFAULT NULL,
    PRIMARY KEY (`mid`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;';
    $db->query($sql);*/


    $template = '<html><head><title>{$mybb->settings[bbname]} - {$lang->mod}</title>{$headerinclude}</head><body>{$header}<div class="scrolls_pane">{$mod_bit}</div><br />{$footer}</body></html>';
    $insert_array = array(
	'title' => 'mod_page',
	'template' => $db->escape_string($template),
	'sid' => '-1',
	'version' => '1',
	'dateline' => TIME_NOW
    );
    $db->insert_query("templates", $insert_array);
    
    $template = '<div class="smalltext" style="padding: 8px;"><a href="forumdisplay.php?fid={$mybb->settings[\'mod_fid\']}">{$lang->mod_featured}</a></div><table cellspacing="0" cellpadding="4" width="100%" border="0" class="windowpane"><tbody>{$mod_index_}</tbody></table><br />';
    $insert_array = array(
	'title' => 'mod_index',
	'template' => $db->escape_string($template),
	'sid' => '-1',
	'version' => '1',
	'dateline' => TIME_NOW
    );
    $db->insert_query("templates", $insert_array);

    $template = '<div class="smalltext windowpane modpane" {$mod_bit_title}>{$lang->mod_mod} {$array[displaystyle]} <a href="{$mybb->settings[bburl]}/mod.php?tid={$array[tid]}"><strong>{$array[subject]}</strong> <sup>{$array[version]}</sup></a> <a href="{$mybb->settings[bburl]}/member.php?action=profile&uid={$array[uid]}">{$formatted_name}</a> <a href="{$mybb->settings[bburl]}/showthread.php?tid={$array[tid]}">&para;</a></div>';
    //$template = '<span class="windowpane">{$array[displaystyle]} <a href="{$mybb->settings[bburl]}/mod.php?tid={$array[tid]}"><strong>{$array[subject]}</strong> <sup>{$array[version]}</sup></a> <a href="{$mybb->settings[bburl]}/member.php?action=profile&uid={$array[uid]}">{$array[username]}</a> <a href="{$mybb->settings[bburl]}/showthread.php?tid={$array[tid]}">&para;</a></span>';
    $insert_array = array(
	'title' => 'mod_bit',
	'template' => $db->escape_string($template),
	'sid' => '-1',
	'version' => '1',
	'dateline' => TIME_NOW
    );
    $db->insert_query("templates", $insert_array);
    
    $template = '<table border="0" class="windowpane" width="100%" cellspacing="0" cellpadding="4"><tbody><tr><td class="bottom_highlight" width="20%">{$lang->mod_game}</td><td class="bottom_highlight">{$PREFIXSELECT}</td></tr><tr><td class="top_highlight bottom_highlight">{$lang->mod_name}</td><td class="top_highlight bottom_highlight"><input type="text" class="textbox" name="subject" size="40" maxlength="85" value="{$subject}" tabindex="1" /></td></tr><tr><td class="top_highlight">{$lang->mod_version}</td><td class="top_highlight"><input type="text" class="textbox" name="version" size="3" maxlength="5" value="{$version}" tabindex="2" /></td></tr></tbody></table><br />';
    $insert_array = array(
	'title' => 'mod_thread',
	'template' => $db->escape_string($template),
	'sid' => '-1',
	'version' => '1',
	'dateline' => TIME_NOW
    );
    $db->insert_query("templates", $insert_array);


    $settings_group = array(
	'gid'		=> 'NULL',
	'name'		=> 'mod',
	'title'		=> 'Mod',
	'description'	=> "Here you can configure Mod.",
	'disporder'	=> $max_disporder + 1,
	'isdefault'	=> '0'
    );
    $db->insert_query('settinggroups', $settings_group);

    $gid = (int) $db->insert_id();
    
    $setting = array(
	'sid'		=> 'NULL',
	'name'		=> 'mod_fid',
	'title'		=> "fid",
	'description'	=> "The fid of ".TABLE_PREFIX."forums that encapsulates Mod.",
	'optionscode'	=> 'text',
	'value'		=> '6',
	'disporder'	=> '1',
	'gid'		=> $gid
    );
    $db->insert_query('settings', $setting);
    
    $setting = array(
	'sid'		=> 'NULL',
	'name'		=> 'mod_regexp_mod',
	'title'		=> "regexp mod",
	'description'	=> "Enter the regular expression for a correct Mod file name. Default at: 7z$",
	'optionscode'	=> 'text',
	'value'		=> '7z$',
	'disporder'	=> '1',
	'gid'		=> $gid
    );
    $db->insert_query('settings', $setting);
    
        $setting = array(
	'sid'		=> 'NULL',
	'name'		=> 'mod_regexp_thumb',
	'title'		=> "regexp thumbnail",
	'description'	=> "Default at: jpg$",
	'optionscode'	=> 'text',
	'value'		=> 'jpg$',
	'disporder'	=> '1',
	'gid'		=> $gid
    );
    $db->insert_query('settings', $setting);

    rebuild_settings();
    

}

function mod_uninstall()
{
    global $db, $lang;
    
    //$db->query('DROP TABLE `'.TABLE_PREFIX.'mod`');
    
    $query = $db->query("DELETE FROM ".TABLE_PREFIX."templates WHERE title = 'mod_page'");
    $query = $db->query("DELETE FROM ".TABLE_PREFIX."templates WHERE title = 'mod_index'");
    $query = $db->query("DELETE FROM ".TABLE_PREFIX."templates WHERE title = 'mod_bit'");
    $query = $db->query("DELETE FROM ".TABLE_PREFIX."templates WHERE title = 'mod_thread'");
    $query = $db->query("DELETE FROM ".TABLE_PREFIX."templates WHERE title = 'mod_subject'");

    $db->delete_query('settinggroups', "name = 'mod'");
    $db->delete_query('settings', "name = 'mod_fid'");
    $db->delete_query('settings', "name = 'mod_regexp'");
    $db->delete_query('settings', "name = 'mod_regexp_mod'");
    $db->delete_query('settings', "name = 'mod_regexp_thumb'");
    
}

function mod_is_installed()
{
    global $db;

    $query = $db->query("
	SELECT  *
	FROM ".TABLE_PREFIX."templates
	WHERE title = 'mod_index'
	");

    $row = $db->num_rows($query) == 1;
    return $row;
}

function mod_activate()
{
    require "../inc/adminfunctions_templates.php";
    find_replace_templatesets("index", '#(\{\$header\})#i', "$1\r\n{\$mod_index}");
    find_replace_templatesets("newthread", '#(<table border="0")#i', "{\$mod_thread}\r\n$1");
    find_replace_templatesets("newthread", '#(\{\$loginbox\}\n<tr)#i', "$1 {\$mod_evade}");
    find_replace_templatesets("newthread", '#(subject")#i', "{\$fuck}$1");
}


function mod_deactivate()
{
    require "../inc/adminfunctions_templates.php";
    find_replace_templatesets("index", '#(\r\n\{\$mod_index\})#i', "");
    find_replace_templatesets("newthread", '#({\$mod_thread\}\r\n)#i', "");
    find_replace_templatesets("newthread", '#( \{\$mod_evade\})#i', "");
    find_replace_templatesets("newthread", '#(\{\$fuck\}subject")#i', "subject\"");
}


function mod_index_start()
{

    global $mod_index, $mybb, $db, $templates, $lang, $theme;
    
    $lang->load("scrolls");
    $lang->load("mod");
    
    $query = $db->query('
	SELECT
	    '.TABLE_PREFIX.'users.uid,
	    '.TABLE_PREFIX.'users.username,
	    '.TABLE_PREFIX.'users.usergroup,
	    '.TABLE_PREFIX.'mod.tid,
	    '.TABLE_PREFIX.'mod.version,
	    '.TABLE_PREFIX.'mod.date,
	    '.TABLE_PREFIX.'threads.subject,
	    '.TABLE_PREFIX.'threadprefixes.displaystyle

	FROM '.TABLE_PREFIX.'mod

	JOIN '.TABLE_PREFIX.'users
	JOIN '.TABLE_PREFIX.'threads
	JOIN '.TABLE_PREFIX.'threadprefixes

	ON
	    '.TABLE_PREFIX.'mod.tid = '.TABLE_PREFIX.'threads.tid AND
	    '.TABLE_PREFIX.'threads.uid = '.TABLE_PREFIX.'users.uid AND
	    '.TABLE_PREFIX.'threadprefixes.pid = '.TABLE_PREFIX.'threads.prefix

	WHERE '.TABLE_PREFIX.'mod.valid = 1
	    
	ORDER BY mid DESC
	LIMIT 3
	');

    // JOIN '.TABLE_PREFIX.'threadprefixes
    // '.TABLE_PREFIX.'threads.prefix

    //$mod_index = "<!--<a href=\"".$mybb->settings['bb_url']."forumdisplay.php?fid=".$mybb->settings['mod_fid']."\">--><strong>".$lang->mod_featured."</strong><!--</a>-->";
    $max = 3;
    while( $c++ < $max )
    {
	$array = $db->fetch_array($query);
	$highlight = "";
	if( $c > 1 ) $highlight .= "top_highlight ";
	if( $c < $max ) $highlight .= "bottom_highlight";
	$mod_index_ .= "<tr><td class=\"$highlight\">";
	
	if( $array[date] != null )
	{
	    $mod_bit_title = date("j-n-Y", $array[date]);
	    if( $array[date] > time() - 86400 )		{ $catchy = $lang->mod_today; $mod_bit_title = $mod_bit_title . ' ' . date("H:i", $array[date]); }
	    elseif( $array[date] > time() - ( 86400 * 2 ) ) { $catchy = $lang->mod_yesterday; $mod_bit_title = $mod_bit_title . ' ' . date("H:i", $array[date]); }
	    elseif( $array[date] > time() - ( 86400 * 3 ) ) $catchy = $lang->mod_days;
	    elseif( $array[date] > time() - ( 86400 * 7 ) ) $catchy = $lang->mod_week;
	    else						$catchy = null;

	    $mod_bit_title = "title=\"".$lang->mod_submitted_on." $catchy $mod_bit_title\"";
	    $formatted_name = format_name($array['username'], $array['usergroup']);
	    eval("\$mod_index_ .= \"".$templates->get("mod_bit")."\";");
	}
	else //if ( $c != $max )
	{
	    $mod_index_ .= '<div style="padding: 4px;" class="smalltext">' . $lang->mod_empty .'</div>';
	}
	/*else
	{
	    $mod_index_ .= '<div style="padding: 4px;" class="smalltext">' . $lang->mod_submit .'</div>';
	}*/
	
	$mod_index_ .= "</td></tr>";
    }
    
    //$mod_index .= "<span class=\"smalltext\" style=\"float: right\">".$lang->mod_index_boast."</span></div>";
    //$mod_index .= "<span class=\"smalltext\">We're only showing 3 here! Go to the Releases forum to see more.</span>";
    
    eval("\$mod_index = \"".$templates->get("mod_index")."\";");
    
}

function mod_newthread_end()
{
    global $mod_thread, $fuck, $mod_evade, $prefixselect, $subject, $mybb, $db, $templates, $lang, $theme;
    
    if( $mybb->input['fid'] != $mybb->settings['mod_fid'] ) return;
    
    $fuck = '_';
    
    $PREFIXSELECT = $prefixselect;
    $prefixselect = '';

    $version = (isset($_POST['version'])) ? $_POST['version'] : "0.9";

    $lang->load("mod");

    // This line is pretty evil:
    //$lang->post_new_thread = "Submit new Mod";
    
    $mod_evade = 'style="display: none;"';
    $mod_subject = "#/";
    
    eval("\$mod_thread = \"".$templates->get("mod_thread")."\";");
}

function mod_editpost_end()
{
    // I am not sure what my plan was here.
    
    //global $thread, $pid, $mybb, $db, $templates, $lang;

    //if( $thread['firstpost'] == $pid ) $lol;
}

/**
 * Making sure everything is right before submission of a thread in the Releases forum.
 */
function mod_datahandler_post_validate_thread($da)
{
    
    global $mybb, $db, $lang;

    if( $da->data['fid'] != $mybb->settings['mod_fid'] )  return;

    $lang->load("mod", true);

    if( ! array_key_exists('prefix', $da->data) || $da->data['prefix'] == 0 )  $da->set_error($lang->mod_noprefix);
    if( ! isset($_POST['version']) || strlen( $_POST['version'] ) == 0 )  $da->set_error($lang->mod_version_error);

    $query = $db->query('
	SELECT COUNT(aid) AS good
	FROM `'.TABLE_PREFIX.'attachments`
	WHERE
	    uid = '.$mybb->user['uid'].' AND
	    posthash = \''.$mybb->input['posthash'].'\'
	    AND
		filename REGEXP \''.$mybb->settings['mod_regexp_mod'].'\'
	');

    $good = $db->fetch_field($query, "good");

    if( $good < 1 ) $da->set_error($lang->mod_attach_7z);
    
}

/**
 * At this point, the thread is validated and inserted, after which we know its tid; which in turn we pass onto the Mod.
 */
function mod_datahandler_post_insert_thread_post($da)
{
    global $mybb, $db, $lang;

    if( $da->data['fid'] != $mybb->settings['mod_fid'] )  return;
    
    $query = $db->query('INSERT INTO '.TABLE_PREFIX.'mod (tid, version, date, valid) VALUES('.$da->tid.', "'.$db->escape_string($_POST['version']).'", '.time().', 1)');
}

/**
 * At updating the thread post, make sure we don't mess up Mod requirements.
 */
function mod_datahandler_post_validate_post($da)
{
    global $mybb, $db, $lang;
    
    if( $da->data['fid'] != $mybb->settings['mod_fid'] )  return;

    $lang->load("mod", true);
    
    // Check if this is the first post in a thread.
    $options = array(
	"order_by" => "dateline",
	"order_dir" => "asc",
	"limit_start" => 0,
	"limit" => 1
    );
    $query = $db->simple_select("posts", "pid", "tid='".intval($da->data['tid'])."'", $options);
    $first_post_check = $db->fetch_array($query);
    if($first_post_check['pid'] != $da->data['pid'])  return;

    $query = $db->query('
	SELECT COUNT(aid) AS good
	FROM `'.TABLE_PREFIX.'attachments`
	WHERE
	    pid = '.$da->data['pid'].' AND
	    filename REGEXP \''.$mybb->settings['mod_regexp'].'\'
    ');

    $good = $db->fetch_field($query, "good");
    if( $good < 1 )
    {
        $da->set_error($lang->mod_attachment_error);
    }
}
?>